#!/usr/bin/env python

# -*- coding: utf-8 -*

"""
GPIO驱动基类，不要实例化此类
"""

from py_code.driver.Driver import Driver
from py_code.driver.Pin import Pin
from typing import List
import RPi.GPIO as GPIO
import logging


class GpioDriver(Driver):
    """
    基于GPIO的驱动
    """
    
    pins: List[Pin]
    """该外设的所有引脚"""

    def pin(self, name):
        logging.debug(f"查找GPIO引脚中（引脚描述：{name}）...")
        for pin in self.pins:
            if pin.description == name:
                logging.debug(f"查找GPIO引脚成功，引脚编号：{pin.id}，引脚描述：{pin.description}")
                return pin
        logging.info(f"未能找到GPIO引脚，引脚描述：{name}")
        return None

    def __init__(self):
        super().__init__()
        self.setGpioMode()
        

    def setGpioMode(self, mode = GPIO.BOARD) -> None:
        """设置GPIO mode"""
        self.mode = mode
        if self.mode != GPIO.getmode():
            logging.warning(f"GPIO模式不正确，当前模式为{GPIO.getmode()}，强制设置模式为: {self.mode}")
            GPIO.setwarnings(False)
            GPIO.setmode(self.mode)
        logging.debug(f"设置GPIO模式为：{self.mode}")

    def pinsInit(self) -> None:
        """引脚初始化，有引脚的建议在open进行调用"""
        for pin in self.pins:
            pin.initGpioPin()
        logging.debug(f"引脚初始化中：{self.pins}")

    def open(self):
        super().open()
        self.pinsInit()

    def close(self):
        logging.debug(f"驱动关闭：{self}")
        for pin in self.pins:
            pin.cleanup()
        return super().close()
